package it.sciuto.turbosmswidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.telephony.SmsManager;
import android.widget.RemoteViews;
import android.widget.Toast;

public class TurboSMSWidget extends AppWidgetProvider {
	public static String ACTION_SEND = "SendSMS";
	public static String ACTION_UPDATE = "Update";
	public static String APP_ID = "appID";
	public static String URI_SCHEME = "turboSMS";

	// public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";

	public static String getNumber(SharedPreferences settings) {
		if (settings != null)
			return settings.getString(ConfigureActivity.PREFERENCE_PHONE_NUMBER, "");
		return "";
	}

	public static String getName(SharedPreferences settings) {
		if (settings != null) {
			String name = settings.getString(ConfigureActivity.PREFERENCE_NAME, "");
			if (!name.equals(""))
				return name;
		}
		return getNumber(settings);
	}

	public String getMessage(SharedPreferences settings) {
		if (settings != null)
			return settings.getString(ConfigureActivity.PREFERENCE_MESSAGE, "");
		return "";
	}

	public static int getMultiSMS(SharedPreferences settings) {
		if (settings != null)
			return Integer.parseInt(settings.getString(ConfigureActivity.PREFERENCE_MULTI_SMS, "0"));
		return 0;
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		for (int appWidgetId : appWidgetIds) {
			RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
			Uri data = Uri.withAppendedPath(Uri.parse(URI_SCHEME + "://widget/id/"), String.valueOf(appWidgetId));

			Intent configIntent = new Intent(context, ConfigureActivity.class);
			configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			configIntent.setData(data);
			configIntent.setAction(ACTION_UPDATE);

			PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, PendingIntent.FLAG_CANCEL_CURRENT);
			remoteViews.setOnClickPendingIntent(R.id.config_button, configPendingIntent);

			Intent smsIntent = new Intent(context, TurboSMSWidget.class);
			smsIntent.putExtra(APP_ID, appWidgetId);
			smsIntent.setData(data);
			smsIntent.setAction(ACTION_SEND);

			PendingIntent smsPendingIntent = PendingIntent.getBroadcast(context, 0, smsIntent, PendingIntent.FLAG_CANCEL_CURRENT);
			remoteViews.setOnClickPendingIntent(R.id.send_button, smsPendingIntent);

			// TODO da testare
			update(context, appWidgetId);

			appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
			update(context, appWidgetId);
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		System.out.println("ACTION " + action);
		if (action.equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
			int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			update(context, appWidgetId);
		} else if (action.equals(ACTION_UPDATE)) {
			int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			update(context, appWidgetId);
		} else if (action.equals(ACTION_SEND)) {
			int appWidgetId = intent.getExtras().getInt(APP_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			sendSMS(context, appWidgetId);
		}
		super.onReceive(context, intent);
	}

	/**
	 * @param context
	 * @param intent
	 */
	public static void update(Context context, int appWidgetId) {

		SharedPreferences settings = context.getSharedPreferences(ConfigureActivity.PREFERENCE_FILENAME + appWidgetId, Context.MODE_PRIVATE);

		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		remoteViews.setTextViewText(R.id.sms_counter_tv, getMultiSMS(settings) + " SMS");
		remoteViews.setTextViewText(R.id.sms_name_tv, getName(settings));

		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
	}

	/**
	 * @param context
	 */
	private void sendSMS(Context context, int appWidgetId) {
		SharedPreferences settings = context.getSharedPreferences(ConfigureActivity.PREFERENCE_FILENAME + appWidgetId, Context.MODE_PRIVATE);

		if (getNumber(settings).equals("") || getMessage(settings).equals("")) {
			Toast.makeText(context, R.string.config_missing, Toast.LENGTH_SHORT).show();
		} else if (getMultiSMS(settings) == 0) {
			Toast.makeText(context, R.string.config_zero_sms, Toast.LENGTH_SHORT).show();
		} else {
			for (int i = 0; i < getMultiSMS(settings); i++) {
				// SEND SMS
				try {
					SmsManager sm = SmsManager.getDefault();
					sm.sendMultipartTextMessage(getNumber(settings), null, sm.divideMessage(getMessage(settings)), null, null);
					Toast.makeText(context, R.string.sent, Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show();
				}
			}
		}
	}
}